package com.atguigu.tingshu.order.receiver;

import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Component
@Slf4j
public class OrderReceiver {

    @Autowired
    private OrderInfoService orderInfoService;

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_ORDER,durable = "true"),
            value = @Queue(value =MqConst.QUEUE_ORDER_PAY_SUCCESS,durable = "true"),
            key = {MqConst.ROUTING_ORDER_PAY_SUCCESS}
    ))
    public void orderPaySuccess(String orderNo,Message message,Channel channel)throws IOException {
        try {
            if (!StringUtils.isEmpty(orderNo)){
                orderInfoService.orderPaySuccess(orderNo);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }



    @RabbitListener(queues = MqConst.QUEUE_CANCEL_ORDER)
    public void orderCancel(String orderNo, Message message, Channel channel){

        try {
            System.out.println("订单取消了");

            if (!StringUtils.isEmpty(orderNo)){
                orderInfoService.orderCancel(orderNo);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

}
